<template>
  <div class="box">
    <a-table
        class="m-t-10"
        :columns="columns"
        :dataSource="dataList"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
        rowKey="id"
        :row-selection="
        role == 'manage'
          ? {
              selectedRowKeys: selectedRowKeys,
              onChange: onSelectChange,
            }
          : null
      "
    >
      <template #title>
        <div class="flex justify-between header-clue">
          <div class="flex-1">
            <a-form ref="searchForm" layout="vertical">
              <a-row :gutter="8">
                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                  <a-form-item>
                    <a-input
                        placeHolder="搜索客户名称"
                        v-model:value="searchParams.contactName"
                    />
                  </a-form-item>
                </a-col>
                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                  <a-form-item>
                    <a-input
                        placeHolder="搜索客户电话"
                        v-model:value="searchParams.contactPhone"
                    />
                  </a-form-item>
                </a-col>
                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                  <a-form-item>
                    <a-input
                        placeHolder="搜索公司名称"
                        v-model:value="searchParams.company"
                    />
                  </a-form-item>
                </a-col>
                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                  <a-form-item>
                    <a-select
                        style="width: 100%"
                        v-model:value="searchParams.villageId"
                        placeholder="请选择意向项目"
                        :options="optionsBuild"
                    />
                  </a-form-item>
                </a-col>
                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                  <a-form-item>
                    <a-select
                        style="width: 100%"
                        v-model:value="searchParams.source"
                        :options="clueSource"
                        placeholder="请选来源"
                    >
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                  <a-form-item>
                    <a-select
                        style="width: 100%"
                        v-model:value="searchParams.clueFrom"
                        :options="optionsClueFrom"
                        placeholder="请选择线索来源"
                    >
                    </a-select>
                  </a-form-item>
                </a-col>

                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                  <a-form-item>
                    <a-select
                        style="width: 100%"
                        v-model:value="searchParams.status"
                        :options="optionsStatus"
                        placeholder="请选择线索状态"
                    >
                    </a-select>
                  </a-form-item>
                </a-col>

                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                  <a-form-item>
                    <a-range-picker
                        class="w-100p"
                        v-model:value="searchParams.created_time"
                        :valueFormat="dateFormatStr"
                        @change="clueTimeChange"
                    />
                  </a-form-item>
                </a-col>

                <a-col>
                  <a-form-item label="">
                    <a-space>
                      <a-button @click="reset">重置</a-button>
                      <a-button type="primary" @click="getDataList(true)">
                        搜索
                      </a-button>
                    </a-space>
                  </a-form-item>
                </a-col>

                <a-col style="margin-left: auto">
                  <a-space>
                    <a-button type="primary" ghost v-permission="['clueManagement','curd','import']"
                              @click="exportClue">导出线索
                    </a-button>
                    <a-button
                        type="primary"
                        ghost
                        @click="appoint"
                        v-if="role == 'manage'"
                    >批量指定分配
                    </a-button
                    >
                  </a-space>
                </a-col>
              </a-row>
            </a-form>
          </div>
        </div>
      </template>

      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'contact_name'">
          <span>{{ record.contact_name }}</span>
        </template>
        <template v-if="column.key === 'contact_phone'">
          <template v-if=" record?.format_type == 2 &&record.full_phone">
               <span>{{
                   record.isFullPhone ? record.full_phone : record.contact_phone
                 }}</span>
            <eye-invisible-outlined class="ml-5" v-if="record.isFullPhone"
                                    @click="record.isFullPhone=false"/>
            <eye-outlined class="ml-5" v-if="!record.isFullPhone" @click="record.isFullPhone=true"/>
          </template>
          <template v-else>
            <span> {{ record.contact_phone }}</span>
          </template>
        </template>
        <template v-if="column.key === 'company'">
          <span>{{ record.company || "--" }}</span>
        </template>
        <!-- <template v-if="column.key === 'status'">
          <div class="flex flex-column">
            <span
              style="display: inline-block; color: #2681f3; font-size: 14px"
              >{{ record.cluestatus?.name }}</span
            >
          </div>
        </template> -->
        <template v-if="column.key === 'clue_from'">
          <span>{{ record.clue_form_txt }}</span>
          <span v-if="record.team_user_name">-{{ record.team_user_name }}</span>
        </template>
        <template v-if="column.key === 'channel_company'">
          <span>{{ record.channel_company_name || '--' }}</span>
        </template>
        <template
            v-if="
            column.key === 'updated_at' ||
            column.key === 'remark' ||
            column.key === 'village_name'
          "
        >
          <span>{{ record[column.key] || "--" }}</span>
        </template>

        <template v-if="column.key === 'requiredArea'">
          <span
          >{{ record.expect_area_min }}-{{ record.expect_area_max }}m²</span
          >
        </template>

        <template v-if="column.key === 'action'">
          <!-- 如果是招商领导 -->
          <a-button
              type="link"
              @click="appointSingle(record.id)"
              v-if="getRole != 0"
          >指定分配
          </a-button
          >
          <!-- 如果是招商专员 -->
          <a-popconfirm
              title="确定领取该线索?  "
              ok-text="确定"
              cancel-text="取消"
              @confirm="receiveClue(record.id)"
          >
            <a-button type="link" v-if="role == 'user' && record.is_receive"
            >领取
            </a-button
            >
          </a-popconfirm>

          <a-button type="link" @click="clueDetail(record.id)">详情</a-button>
        </template>
      </template>
    </a-table>

    <!-- 指定分配 -->
    <a-modal
        v-model:visible="appointVisible"
        title="指定分配"
        okText="保存"
        @ok="handleOk"
    >
      <a-form ref="assignRef" :model="assignData">
        <a-form-item
            label="选择分配成员"
            name="user_id"
            :rules="[{ required: true, message: '请选择分配成员' }]"
        >
          <a-select
              placeholder="请选择分配成员"
              :options="userList"
              v-model:value="assignData.user_id"
          >
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>

  <!-- 详情 -->
  <ClueDetail
      :visible="detailVisible"
      :id="detailId"
      :optionsBuild="optionsBuild"
      @closeDetail="() => (detailVisible = false)"
      @back="refreshList"
  />
</template>

<script>
import {EyeInvisibleOutlined, EyeOutlined, QuestionCircleOutlined} from "@ant-design/icons-vue";
import {reactive, ref, toRefs, computed, watch} from "vue";
import request from "../../../../common/utils/request";
import {message} from "ant-design-vue";
import ClueDetail from "./ClueDetail.vue";

const dateFormatStr = "YYYY-MM-DD";
export default {
  components: {
    EyeOutlined, EyeInvisibleOutlined,
    QuestionCircleOutlined,
    ClueDetail,
  },
  props: {
    activeKey: {
      type: String,
      default: "",
    },
    optionsClueFrom: {
      type: Array,
      default: () => [],
    },
    optionsBuild: {
      type: Array,
      default: () => [],
    },
    optionsStatus: {
      type: Array,
      default: () => [],
    },
    role: {
      type: String,
      default: "manage", //默认manage  专员user
    },
    clueSource: {
      type: Array,
      default: () => [],
    }
  },
  setup(props) {
    const state = reactive({
      list: [],
      itemList: [],
      appointVisible: false,
      idList: {},
      chooseMemberVisible: false,
      canSelect: false,
      selectedRowKeys: [],
      isDetail: false,
      isSingle: true, //是否单项指派  还是多个指派
      getRole: 0,
    });
    const assignData = reactive({
      user_id: undefined,
    });

    const columns = [
      {
        title: "客户名称",
        key: "contact_name",
        width: 200,
      },
      {title: "客户电话", key: "contact_phone", width: 200},
      {
        title: "公司",
        key: "company",
        width: 200,
      },

      {
        title: "线索来源",
        key: "clue_from",
        width: 200,
      },
      {
        title: "所属渠道公司",
        key: "channel_company",
        width: 240,
      },
      {
        title: "更新时间",
        key: "updated_at",
        width: 200,
      },

      {
        title: "意向项目",
        key: "village_name",
        width: 200,
      },
      {
        title: "需求面积段",
        key: "requiredArea",
        width: 200,
      },
      {
        title: "备注",
        key: "remark",
        width: 200,
      },
      {
        title: "操作",
        key: "action",
        width: 200,
      },
    ];

    const page = ref(1);
    const limit = ref(10);
    const total = ref(0);
    const dataList = ref([]);
    const pagination = computed(() => ({
      total: total.value,
      current: page.value,
      pageSize: limit.value,
      showSizeChanger: true,
    }));

    const searchParams = reactive({
      contactName: "",
      contactPhone: "",
      company: "",
      villageId: undefined,
      clueFrom: undefined,
      status: undefined,
      created_time: undefined,
      startDate: undefined,
      endDate: undefined,
      source: undefined,
    });

    const clueTimeChange = (date) => {
      state.created_time = date;
    };

    const loading = ref(false);
    const handleTableChange = (pager, filters, sorter) => {
      page.value = pager.current;
      limit.value = pager.pageSize;
    };

    const getDataList = (val) => {
      const param = {
        page: page.value,
        pageSize: limit.value,
        //   managerAuth: managerAuth.value,
        type: "pool",
      };
      Object.keys(searchParams).forEach((key) => {
        if (key != "created_time") {
          if (searchParams[key]) {
            param[key] = searchParams[key];
          }
        } else {
          if (searchParams[key]) {
            param.startDate = searchParams[key][0];
            param.endDate = searchParams[key][1];
          }
        }
      });

      loading.value = true;
      request
          .get("/org", "/business/clue", param)
          .then((res) => {
            console.log(res);
            dataList.value = res.list.map((item) => {
              return {
                ...item,
                isFullPhone: item.format_type == 1,
              };
            });
            total.value = res.total;
          })
          .finally(() => {
            loading.value = false;
          });
    };

    const onSelectChange = (selectedRowKeys) => {
      console.log("selectedRowKeys changed: ", selectedRowKeys);
      state.selectedRowKeys = selectedRowKeys;
    };

    const userList = ref([]);
    const getTeemUserList = () => {
      request
          .get("/org", "/business/customerTeam/teamUserIndex")
          .then((res) => {
            userList.value = res.data.map((item) => {
              return {
                label: item.name,
                value: item.uid,
              };
            });
          });
    };

    const getRole = () => {
      request
          .get("/org", "/business/customerTeam/UserRoleInfo", {})
          .then((res) => {
            console.log(res);
            state.getRole = res.role;
          });
    };

    const init = () => {
      getRole();
      getTeemUserList();
      getDataList();
    };

    watch([page, limit], () => {
      getDataList();
    });

    watch(
        () => props.activeKey,
        (val) => {
          if (val == "pool") {
            init();
          }
        },
        {immediate: true}
    );

    const reset = () => {
      Object.keys(searchParams).forEach((key) => {
        searchParams[key] = undefined;
      });
      console.log("searchParams", searchParams);
      getDataList();
    };

    getDataList();

    const refreshList = () => {
      detailVisible.value = false;
      page.value = 1;
      getDataList();
    };

    // 导出线索
    let timer = null;
    const iframe = document.createElement("iframe");
    const exportClue = () => {
      console.log("导出线索")
      if (timer) {
        message.warn("操作过于频繁，请稍后尝试");
        return;
      }
      let params = {
        type: 'pool',
        ids: state.selectedRowKeys
      };
      for (let key in searchParams) {
        if (searchParams[key]) {
          params[key] = searchParams[key];
        }
      }
      console.log(params)
      request
          .post("/org", "/business/clue/import", params)
          .then((res) => {
            iframe.src = res.result.fileUrl;
            iframe.style.display = "none";
            document.body.appendChild(iframe);
            setTimeout(() => {
              document.body.removeChild(iframe);
            }, 1000);
            message.success("导出成功,请等待文件生成");
            timer = setTimeout(() => {
              timer = null;
            }, 20000);
          });
    };


    // 批量指定分配
    const appoint = () => {
      state.isSingle = false;
      console.log(state.selectedRowKeys, "1111");
      if (state.selectedRowKeys.length == 0) {
        message.error("请先选择需要分配的线索");
        return;
      }
      state.appointVisible = true;
    };
    // 指定分配
    const clue_id = ref(0);
    const appointSingle = (val) => {
      state.isSingle = true;
      clue_id.value = val;
      state.appointVisible = true;
    };

    const assignRef = ref();
    const handleOk = () => {
      console.log(assignRef.value);
      assignRef.value.validateFields().then(() => {
        let param = {
          user_id: assignData.user_id,
        };
        if (state.isSingle) {
          //单个指派
          param.clue_id = [clue_id.value];
        } else {
          //多个指派
          param.clue_id = state.selectedRowKeys;
        }
        console.log(param);

        request
            .post("/org", "/business/clue/assignPoolClue", param)
            .then((res) => {
              console.log(res);
              message.success("指派成功");
              state.appointVisible = false;
              getDataList();
            })
            .finally(() => {
              assignRef.value.resetFields();
            });
      });
    };

    // 详情
    const detailId = ref(0);
    const detailVisible = ref(false);
    const clueDetail = (val) => {
      state.isDetail = true;
      detailId.value = String(val);
      detailVisible.value = true;
    };

    // 领取线索
    const receiveClue = (val) => {
      request
          .post("/org", "/business/clue/receivePoolClue", {
            id: val,
          })
          .then((res) => {
            console.log(res);
            message.success("领取线索成功");
            getDataList();
          });
    };

    return {
      ...toRefs(state),
      columns,
      searchParams,
      getDataList,
      dataList,
      handleTableChange,
      pagination,
      dateFormatStr,
      reset,
      appoint,
      handleOk,
      appointSingle,
      clueDetail,
      receiveClue,
      userList,
      onSelectChange,
      loading,
      detailVisible,
      detailId,
      refreshList,
      assignRef,
      assignData,
      clueTimeChange,
      exportClue,
    };
  },
};
</script>

<style lang="less" scoped>
.box {
  padding: 10px;

  .header-clue {
    padding: 0 16px;
  }

  .header {
    background-color: rgb(240, 242, 245);
    padding: 10px;

    .num-info {
      color: #2681f3;
      font-size: 30px;
      max-width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      word-break: break-all;
    }
  }

  .m-t-10 {
    margin-top: 10px;
  }
}

.user-tag :deep(.ant-tag) {
  border-radius: 20px !important;
  padding: 0 12px 0 0 !important;
  background: #f1f1f1;
  border: none;
}

:deep(.ant-table-title) {
  padding: 0;
}
</style>
